//
//  HomeTableViewController.swift
//  WeiBoSwift
//  Created by Jacky Sun on 16/4/18.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
let Iditifier = "zxcvbnm"

class HomeTableViewController: FDBaseTableViewController {

    var titleBtn : TitleButton?
    
    var modelArr : [Status]?{// 加载模型数组
        didSet {
        tableView.reloadData()
        }
    }
    
        override func viewDidLoad() {
        super.viewDidLoad()
        if(!UserAccount.isLogin()){
             notLoginView?.showDifferentText(true, imgStr: "visitordiscover_feed_image_house", alertStr: "这里是首页啊，大家赶快登录")
            return
        }
      //  let xx = UserAccount.getUserAccount()?.access_token
        setUpNavigationBar()
            loadData()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.changePopView), name: PopUpViewAnimatorWillShow, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.changePopView), name: PopUpViewAnimatorWillDismiss, object: nil)
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.showPIctureBrowser(_:)), name: FDPostNotifaByPIctureSelected, object: nil)
    }
    
    /**
     展示图片浏览器
     
     - parameter notifi:
     */
    func  showPIctureBrowser(notifi: NSNotification){
        
      print(notifi.userInfo)
        
        
        guard let index = notifi.userInfo![FDPictureSelectedIndex] as? Int else{
            print("没有indexPath")
            return
        }
        guard let urls = notifi.userInfo![FDPictureSelectedNSURL] as? [NSURL] else{
            print("没有配图")
            return
        }
        
        let VC: PhotoBrowserViewController = PhotoBrowserViewController(index: index, urls: urls)
        
         presentViewController(VC, animated: true, completion: nil)
        
    }
    
        func changePopView() {
        let btn = navigationItem.titleView  as! UIButton
        btn.selected = !btn.selected
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    // 设置导航栏
     func setUpNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem.createIMgBarbuttonItem("navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.homeLeftClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem.createIMgBarbuttonItem("navigationbar_pop", target: self, action: #selector(HomeTableViewController.homeRightClick))
        
        titleBtn = TitleButton()
        titleBtn!.setTitle(UserAccount.getUserAccount()?.screen_name, forState: UIControlState.Normal)
        titleBtn!.addTarget(self, action: #selector(HomeTableViewController.titleClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        titleBtn!.sizeToFit()
       navigationItem.titleView = titleBtn
//        
        if tableView == nil {
            print("tableview 为空")
            return
        }
        //MARK - 注册cell
        tableView.registerClass(ForwardStatusCell.self, forCellReuseIdentifier: HomeTableCellIdntifier.ForwardCell.rawValue)
        tableView.registerClass(OriginalStatusCell.self, forCellReuseIdentifier: HomeTableCellIdntifier.OriginalCell.rawValue)
        
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
          refreshControl = FDRefreshControl()
           refreshControl?.addTarget(self, action: #selector(HomeTableViewController.loadData), forControlEvents: UIControlEvents.ValueChanged)
        }
    
    //MARK -m 加载网络数据
    /**
     获取微博数据
     如果想调用一个私有的方法:
     1.去掉private
     2.@objc, 当做OC方法来处理
     */
  @objc func loadData()
    {
        
        // 加载网络数据
        
        //1. 默认是下拉刷新
        var since_id = self.modelArr?.first?.id ?? 0
        var max_id = 0
        
        //2\ 如果标示着上啦
        if flagForPushstatus{
            since_id = 0
            max_id = self.modelArr?.last?.id ?? 0
        }
        
        print("since= \(since_id),   max_id = \(max_id)")
        
        Status.loadStatusHttpRequest(since_id, max_id: max_id) { (modelArr, error) in
            // 结束刷新
            
            self.refreshControl?.endRefreshing()
            // 还原标示xinxi
            self.flagForPushstatus = false
            
            if error != nil {
                return
            }
            if since_id > 0{
                // 刷新提醒
                self.animWithAlertLab(modelArr!)
                self.modelArr = modelArr! + self.modelArr!
            }
            else if max_id > 0 {
                self.modelArr = self.modelArr! + modelArr!
            }
            else{
                self.modelArr = modelArr
             }
            
        }
    }

    
    /**
     弹出用户菜单
     
     - parameter btn: btn
     */
     func titleClick(btn: TitleButton) {
     //   btn.selected = !btn.selected
        
       let sb = UIStoryboard(name: "PopupViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        // 设置专场代理
        // 默认情况下modal会移除以前控制器的view, 替换为当前弹出的view
        // 如果自定义转场, 那么就不会移除以前控制器的view
        vc!.transitioningDelegate = popUpAnimator
        vc!.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc!, animated: true, completion: nil)
    }

     func homeLeftClick() {
      print(#function)
    }
   
     func homeRightClick() {
        print(#function)
        let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    /**
     舒心后的提醒动画
     
     - parameter modelArr: <#modelArr description#>
     */
     func animWithAlertLab(modelArr: [Status]?){
        self.alertLab.hidden = false
        self.alertLab.text = modelArr?.count>0 ? "swift君刷新到\(modelArr!.count)条数据" : "暂未刷新到新数据"
        UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
        self.alertLab.transform = CGAffineTransformMakeTranslation(0, 44)

        }) { (_) in
            NSThread.sleepForTimeInterval(1.0)
            UIView.animateWithDuration(1.0, animations:
            {
                self.alertLab.transform = CGAffineTransformIdentity
            }){(_) in
                self.alertLab.hidden = true
            }
            }
        
    }
    
    ///
    private  lazy var popUpAnimator: PopVIewAnimator = {
       let pop = PopVIewAnimator()
        pop.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350)
        return pop
    }()
    
     /// 标示是不是上啦加载
    private lazy var flagForPushstatus: Bool = false
    
    // MARK: - 缓存行高
    var rowCache: [Int: CGFloat] = [Int: CGFloat]()
        override func didReceiveMemoryWarning() {
        rowCache.removeAll()
    }
    
    // MARK: - 懒加载lab提醒
    private lazy var alertLab: UILabel = {
        let lab = UILabel()
        lab.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 44)
        self.navigationController?.navigationBar.insertSubview(lab, atIndex: 0)
        lab.backgroundColor = UIColor.orangeColor()
        lab.font = UIFont.systemFontOfSize(14)
        lab.textColor = UIColor.whiteColor()
        lab.hidden = true
        lab.textAlignment = NSTextAlignment.Center
        return lab
    }()
}


extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (modelArr != nil) ? modelArr!.count : 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let status =  modelArr![indexPath.row]
         let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableCellIdntifier.returnCellIdntifier(status), forIndexPath: indexPath) as! StatusHomeCell
         cell.status = status
        
        
        let count = modelArr?.count ?? 0
        if indexPath.row == (count-1) && !flagForPushstatus{
            flagForPushstatus = true
            loadData()
        }
        
        
        return cell
    }

    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //1. 取出模型
        let status = modelArr![indexPath.row]

        if let height = rowCache[status.id]{
            return height
        }
    
          let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableCellIdntifier.returnCellIdntifier(status)) as! StatusHomeCell
          rowCache[status.id] = cell.getCellHeight(status)
         return  rowCache[status.id]!
    }
}